﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web;

using Seven.Tools;
using Seven.Tools.Helper;

namespace Seven.Web.Mvc
{
    /// <summary>
    /// 表示一个类，该类用于将 JSON 序列化字符串格式的内容发送到响应。
    /// </summary>
    public class JsonSerializeResult : JsonResult
    {
        /// <summary>
        /// 初始化类型的 <see cref="JsonSerializeResult"/> 新实例。
        /// </summary>
        public JsonSerializeResult()
        {
            this.JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.DenyGet;
        }

        /// <summary>
        /// 获取或设置一个值，该值表示序列化时是否转换枚举Value为枚举Text。
        /// </summary>
        public bool EnumTransfer { get; set; }

        /// <summary>
        /// 获取或设置一个值，该值表示序列化时对日期数据的格式化类型
        /// </summary>
        public DateFormatType DateFormatType { get; set; }

        /// <summary>
        /// 通过从 System.Web.Mvc.ActionResult 类继承的自定义类型，启用对操作方法结果的处理。
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            Check.NotNull(context);
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(Resources.JsonRequest_GetNotAllowed);
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = String.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if ((int)this.DateFormatType == 0)
            {
                this.DateFormatType = Tools.Helper.DateFormatType.None;
            }

            if (this.Data != null)
            {
                response.Write(JsonHelper.SerializeObject(this.Data, this.EnumTransfer, this.DateFormatType));
            }
        }
    }
}
